import Mn from 'backbone.marionette';
import { updateSelectOptions, ajax_call} from '../tools.js';
import Radio from 'backbone.radio';

var template = require('./templates/ToggleButtonWidget.mustache');

const ToggleButtonWidget = Mn.View.extend({
    template:template,
    ui: {
        radios: 'input[type=radio]',
    },
    events: {
        'change @ui.radios': 'onChange',
   },
    initialize(){
      this.updateSelectOptions();
    },
    updateSelectOptions() {
        let options = this.model.get('options');
        updateSelectOptions(
            options.buttons,
            options.current_value,
            "value",
        );
    },
    onChange(event){
        let stringValue = event.target.value;

        let opts = this.model.get('options');
        // Allows to have non-string value in current_value
        let selectedButton = _.find(
            opts.buttons,
            button => button.value.toString() === stringValue
        );
        let typedValue = selectedButton.value;

        opts.current_value = typedValue;
        this.model.set('options', opts);

        this.updateSelectOptions();
        this.render();

        this.trigger('status:change', typedValue);
        ajax_call(
            this.model.get('options').url,
            {'submit': typedValue},
            'POST',
            {success: this.onSuccess.bind(this)},
        );
    },
    onSuccess(){
        this.trigger('status:changed', this.model);
    },
    templateContext(){
        let options = this.model.get('options');
        return {
            name: options.name,
            toggle_label: options.toggle_label || "Changer le statut en",
            buttons: options.buttons,
        }
    },
});

export default ToggleButtonWidget;
